package pl.shenlon.poker.gui;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;

import net.miginfocom.swing.MigLayout;
import pl.shenlon.assets.Assets;
import pl.shenlon.poker.game.PokerPlayer;

public class PlayerView extends JComponent implements Observer {

	public static final int PLAYER_FACES_COUNT = 115;

	public static final Random rnd;

	static {
		rnd = new Random();
	}

	private PokerPlayer player;
	private JLabel playerImage, cashLabel, statisticsLabel;

	{
		initComponent();
	}

	public PlayerView() {

	}

	public PlayerView(PokerPlayer player) {
		setPokerPlayer(player);
	}

	private void initComponent() {
		playerImage = new JLabel();
		playerImage.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		cashLabel = new JLabel("Gotówka");
		statisticsLabel = new JLabel("Statystyka (W/T/L)");

		setLayout(new MigLayout());
		add(playerImage, "spany");
		add(cashLabel, "wrap");
		add(statisticsLabel, "wrap");
	}

	public void setPlayerImage(Image image) {
		playerImage.setIcon(new ImageIcon(image));
	}

	public void setPokerPlayer(PokerPlayer player) {
		if (this.player != null) {
			this.player.deleteObserver(this);
		}
		this.player = player;
		this.player.addObserver(this);

		setPlayerImage((BufferedImage) Assets.get("players",
				String.valueOf(rnd.nextInt(PLAYER_FACES_COUNT))));
		update(null, null);
	}

	@Override
	public void update(Observable object, Object arg) {
		cashLabel.setText("Gotówka " + player.getCash() + " $");
		statisticsLabel.setText(String.format("Statystyka (W/T/L) %d/%d/%d",
				player.getWins(), player.getTies(), player.getLoses()));
	}
}